<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\BillDelivery;
use app\common\model\GoodsType;
use app\common\model\OrderSub;
use app\common\model\Products;
use app\common\model\Shop;
use app\common\model\ShopCate;
use app\common\model\ShopExpress;
use app\common\model\ShopShip;
use app\common\model\ShopSort;
use app\common\model\UserToken;
use app\common\model\OrderSub as orderModel;
use think\Exception;

/***
 * 店铺卖家接口
 */
class Seller extends Api
{
    /**
     * 获取商品类型
     */
    public function goodsType(){
        $gtype=new GoodsType();
        $result=$gtype->getList();
        if(!$result['status']){
            return returnData(0,'获取数据失败');
        }
        return returnData(1,'success',$result['data']);
    }
    /**
     * 保存商品
     * @return array
     */
    public function saveGoods(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $data=$this->request->post();
            $data['shop_id']=$shop_id;
            $data['bn']=get_sn(3);
            $data['image_id']=reset($data['img_ids']);
            $data['images']=$data['img_ids'];#图片列表
            $data['costprice']=$data['price'];#成本价
            unset($data['img_ids']);
            $goods=new \app\common\model\Goods();

            if(!empty($data['id'])) {
                $validate  = new \app\common\validate\Goods();
                if (!$validate->scene('edit')->check($data)) {
                    return returnData(0,$validate->getError());
                }
            } else {
                $validate = new \app\common\validate\Goods();
                if (!$validate->check($data)) {
                    return returnData(0,$validate->getError());
                }
            }
            $goods->startTrans();
            list($res,$info)=$goods->saveGoods($data);
            if(!$res){
                $goods->rollback();
                return returnData(0,$info);
            }
            $goods->commit();
            return returnData(1,'success');
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 上架或下架商品
     * @return array
     */
    public function doGround(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $goods=new \app\common\model\Goods();
            $id=$this->request->param('id',0);
            #类别，1上架，2下架
            $type=$this->request->param('type',1);
            $data=[
                'id'=>$id,
                'type'=>$type
            ];
            list($res,$info)=$goods->doGround($data);
            if(!$res){
                return returnData(0,$info);
            }
            return returnData(1,$info);
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 修改商品分类
     * @return array
     */
    public function moveGoods(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $goods=new \app\common\model\Goods();
            $id=$this->request->param('id',0);
            $sort_id=$this->request->param('sort_id',0);
            $data=[
                'id'=>$id,
                'sort_id'=>$sort_id
            ];
            list($res,$info)=$goods->moveGoods($data);
            if(!$res){
                return returnData(0,$info);
            }
            return returnData(1,$info);
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 删除上架商品
     */
    public function delGoods(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $goods=new \app\common\model\Goods();
            $id=$this->request->param('id',0);
            $result=$goods->delGoods($id);
            if(!$result['status']){
                return returnData(0,$result['msg']);
            }
            return returnData(1,$result['msg']);
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 删除运费模版
     * @return array
     */
    public function delExpress(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $shopExp=new ShopExpress();
            $id=$this->request->param('id',0);
            $data=[
                'id'=>$id
            ];
            list($res,$info)=$shopExp->delExp($data);
            if(!$res){
                return returnData(0,$info);
            }
            return returnData(1,$info);
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 运费模版
     * @return array
     */
    public function expressList(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',20);
        $shopExp=new ShopExpress();
        $data=[
            'shop_id'=>$shop_id,
            'page'=>$page,
            'limit'=>$limit
        ];
        list($res,$info)=$shopExp->getList($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success',$info);
    }
    /**
     * 保存运费模版
     * @return array
     */
    public function saveExpress(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $shopExp=new ShopExpress();
        $data=$this->request->post();
        if(empty($data['name'])){
            return returnData(0,'请输入模版姓名');
        }
        if(empty($data['logi_code'])){
            return returnData(0,'请选择快递公司');
        }
        if($data['is_free']==2){
            if(empty($data['first_price'])){
                return returnData(0,'请输入首重费用');
            }
            if(empty($data['first_unit'])){
                return returnData(0,'请选择首重单位');
            }
            if(empty($data['renew_price'])){
                return returnData(0,'请输入续重费用');
            }
            if(empty($data['renew_unit'])){
                return returnData(0,'请选择续重单位');
            }
        }
        $data['shop_id']=$shop_id;
        list($res,$info)=$shopExp->saveExpress($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'保存成功');
    }
    /**
     * 显示运费模版
     * @return array
     */
    public function showExpress(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $shopExp=new ShopExpress();
        $id=$this->request->param('id',0);
        $info=$shopExp->where(['id'=>$id,'shop_id'=>$shop_id])->find();
        if(!$info){
            return returnData(0,'获取数据失败');
        }
        $info['first_weight']=config('params.ship_unit')[$info['first_unit']];
        $info['renew_weight']=config('params.ship_unit')[$info['renew_unit']];
        return returnData(1,'success',$info);
    }
    /**
     * 获取物流公司
     */
    public function getLogisList(){
        $expModel=new ShopExpress();
        list($res,$info)=$expModel->getLogis();
        if(!$res){
            return returnData(0,'获取数据失败');
        }
        return returnData(1,'success',$info);
    }
    /**
     * 删除发货地址
     * @return array
     */
    public function delAddress(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $shopShip=new ShopShip();
            $id=$this->request->param('id',0);
            $data=[
                'id'=>$id
            ];
            list($res,$info)=$shopShip->delShip($data);
            if(!$res){
                return returnData(0,$info);
            }
            return returnData(1,$info);
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 显示发货地址
     * @return array
     */
    public function showAddress(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $shopShip=new ShopShip();
        $id=$this->request->param('id',0);
        $info=$shopShip->where(['id'=>$id,'shop_id'=>$shop_id])->find();
        if(!$info){
            return returnData(0,'获取数据失败');
        }
        $info['area_name'] = get_area($info['area_id']);

        return returnData(1,'success',$info);
    }
    /**
     * 添加发货地址
     */
    public function saveAddress(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $shopShip=new ShopShip();
        $data=$this->request->post();
        if(empty($data['name'])){
            return returnData(0,'请输入发货人姓名');
        }
        if(empty($data['address'])){
            return returnData(0,'请输入发货人地址');
        }
        if(empty($data['mobile']) || strlen($data['mobile'])!==11){
            return returnData(0,'请输入发货人手机号码');
        }

        $data['shop_id']=$shop_id;
        list($res,$info)=$shopShip->updateShip($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'保存成功');
    }
    /**
     * 店铺发货地址
     */
    public function addressList(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',20);
        $shopShip=new ShopShip();
        $data=[
            'shop_id'=>$shop_id,
            'page'=>$page,
            'limit'=>$limit
        ];
        list($res,$info)=$shopShip->getList($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success',$info);
    }
    /**
     * 删除分类
     * @return array
     */
    public function delCate(){
        try{
            $uid=$this->userId;
            $shop=new Shop();
            $shop_id=$shop->getShopId($uid);
            if(!$shop_id){
                return returnData(0,'获取数据失败');
            }
            $shopCate=new ShopCate();
            $id=$this->request->param('id',0);
            $data=[
                'id'=>$id
            ];
            list($res,$info)=$shopCate->delCate($data);
            if(!$res){
                return returnData(0,$info);
            }
            return returnData(1,$info);
        }catch (Exception $e){
            return returnData(0,$e->getMessage());
        }
    }
    /**
     * 显示分类详情
     * @return array
     */
    public function showCate(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $shopCate=new ShopCate();
        $id=$this->request->param('id',0);
        $info=$shopCate->where(['id'=>$id,'shop_id'=>$shop_id])->find();
        if(!$info){
            return returnData(0,'获取数据失败');
        }
        return returnData(1,'success',$info);
    }
    /**
     * 添加或更新商品分类
     */
    public function saveCate(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $shopCate=new ShopCate();
        $id=$this->request->param('id',0);
        $name=$this->request->param('name','','trim');
        $indexid=$this->request->param('indexid',100);
        if(empty($name)){
            return returnData(0,'请输入商品分类');
        }
        $data=[
            'shop_id'=>$shop_id,
            'name'=>$name,
            'indexid'=>$indexid,
            'id'=>$id
        ];
        list($res,$info)=$shopCate->updateCate($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'保存成功');
    }
    /**
     * 前端显示店铺自定义商品分类
     */
    public function getCateList(){
        $shop_id=$this->request->param('shop_id/d',0);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',20);
        $shopCate=new ShopCate();
        $data=[
            'shop_id'=>$shop_id,
            'page'=>$page,
            'limit'=>$limit
        ];
        list($res,$info)=$shopCate->getList($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success',$info);
    }
    /**
     * 店铺自定义商品分类
     */
    public function cateList(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',20);
        $shopCate=new ShopCate();
        $data=[
            'shop_id'=>$shop_id,
            'page'=>$page,
            'limit'=>$limit
        ];
        list($res,$info)=$shopCate->getList($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success',$info);
    }
    /**
     * 店铺宝贝管理
     */
    public function goodsList(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $type=$this->request->param('type',1);
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',20);
        $goods=new \app\common\model\Goods();
        $where[]=[['shop_id','=',$shop_id]];
        $sort='sort asc';
        switch ($type){
            case 1:#已上架
                $where[]=[['marketable','=',1]];
                break;
            case 2:#已下架
                $where[]=[['marketable','=',2]];
                break;
        }
        $result=$goods->getList('*',$where,$sort,$page,$limit);
        if(!$result['status']){
            return returnData(0,'获取数据失败');
        }
        return returnData(1,'success',['list'=>$result['data'],'total'=>$result['total']]);
    }
    /**
     * 店铺浏览
     */
    public function onViews(){
        $shop_id=$this->request->param('id',0);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $uid=$this->userId;
        $data=[
            'uid'=>$uid,
            'shop_id'=>$shop_id,
        ];
        $shop=new Shop();
        list($res,$info)=$shop->onViews($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success');
    }
    /**
     * 店铺收藏
     */
    public function onFavs(){
        $shop_id=$this->request->param('id',0);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $uid=$this->userId;
        $data=[
            'uid'=>$uid,
            'shop_id'=>$shop_id,
        ];
        $shop=new Shop();
        list($res,$info)=$shop->onFavs($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success');
    }
    /**
     * 店铺主页
     */
    public function myHome(){
        $shop_id=$this->request->param('id',0);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $token = $this->request->param('token','');//token值 会员登录后传
        $uid = 0;
        if($token){
            $userTokenModel = new UserToken();
            $result         = $userTokenModel->checkToken($token);
            if ($result['status']) {
                $uid = $result['data']['user_id'];
            }
        }
        #查询店铺信息
        $data=[
            'uid'=>$uid,
            'shop_id'=>$shop_id
        ];
        $shop=new Shop();
        list($res,$info)=$shop->shopInfo($data);
        if(!$res){
           return returnData(0,$info);
        }
        return returnData(1,'success',$info);
    }
    /**
     * 店铺主页商品
     */
    public function myGoods(){
        $shop_id=$this->request->param('id',0);
        if(!$shop_id){
            return returnData(0,'获取数据失败');
        }
        $type=$this->request->param('type',1);
        $sort_id=$this->request->param('sort_id',0);
        $page=$this->request->param('page',1);
        $limit=$this->request->param('limit',20);
        $goods=new \app\common\model\Goods();
        $where[]=[
            ['shop_id','=',$shop_id],
            ['marketable','=',1]
        ];
        $sort='sort asc';
        switch ($type){
            case 1:#热门
                $where[]=[['is_hot','=',1]];
                break;
            case 2:#推荐
                $where[]=[['is_recommend','=',1]];
                break;
            case 3:#最新
                $sort='ctime desc,id desc';
                break;
        }
        if(!empty($sort_id)){
            $where[]=[['shop_cat_id','=',$sort_id]];
        }
        $result=$goods->getList('*',$where,$sort,$page,$limit);
        if(!$result['status']){
            return returnData(0,'获取数据失败');
        }
        return returnData(1,'success',['list'=>$result['data'],'total'=>$result['total']]);
    }
    /**
     * 订单详情
     */
    public function orderDetail(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        if(empty($shop_id)){
            return returnData(0,'操作失败');
        }
        $order_id=$this->request->param('order_id');
        if(!$order_id){
            return returnData(0,'操作失败');
        }
        #订单信息
        $orderModel=new OrderSub();
        $order=$orderModel->getOrderInfoByOrderID($order_id);
        if(!$order){
            return returnData(0,'获取失败');
        }
        return returnData(1,'success',$order);
    }
    /**
     * 订单状态统计
     */
    public function orderStatusNum(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        $params=[
            'shop_id'     => $shop_id,
            'ids'         => $this->request->param('ids','1,2,3,4'),
            'isAfterSale' => $this->request->param('isAfterSale', false)
        ];
        $model = new orderModel();
        $data  = $model->getOrderStatusNum($params);
        if(!$data){
            return returnData(0,'获取失败',$data);
        }
        return returnData(1,'success',$data);
    }
    /**
     * 订单发货
     */
    public function deliverGoods(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        $order_id=$this->request->param('order_id');
        if(!$order_id){
            return returnData(0,'操作失败');
        }
        $logi_code=$this->request->param('logi_code');
        if(!$logi_code){
            return returnData(0,'请选择快递公司');
        }
        $logi_no=$this->request->param('logi_no');
        if(!$logi_no){
            return returnData(0,'请输入快递单号');
        }
        $memo=$this->request->param('memo');

        #发货单
        $billDeliveryModel = new BillDelivery();
        $result = $billDeliveryModel->ship($order_id, $logi_code, $logi_no, 0, $memo, $shop_id);
        if(!$result['status']){
            return returnData(0,$result['msg']);
        }
        return returnData(1,'success',$result['data']);
    }
    /**
     * 订单列表
     */
    public function orderlist(){
        $uid=$this->userId;
        $shop=new Shop();
        $shop_id=$shop->getShopId($uid);
        $params = [
            'status'  => $this->request->param('status'),
            'page'    => $this->request->param('page'),
            'limit'   => $this->request->param('limit'),
            'shop_id' => $shop_id
        ];
        $model = new orderModel();
        $result  = $model->getListFromWxApi($params);
        $data=[
            'list'=>$result['data'],
            'count'=>$result['count'],
            'page'=>$params['page'],
            'limit'=>$params['limit'],
            'status'=>$params['status']
        ];
        return returnData(1,'success',$data);

    }
    /**
     * 我的店铺信息
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function myShop(){
        $user_id = $this->userId;
        $shop=Shop::where(['uid'=>$user_id])->withJoin(['shopsort'=>['name']])->find();
        return returnData(1,'success',$shop);
    }
    /**
     * 获取店铺类目
     */
    public function cate(){
        $sort=new ShopSort();
        $list=$sort->getList();
        return returnData(1,'success',$list);
    }
    /**
     * 店铺资料首次填写
     */
    public function onApply(){
        $user_id = $this->userId;
        $data=$this->request->post();
        $data['uid']=$user_id;
        $shop=new Shop();
        list($res,$info)=$shop->setting($data);
        if(!$res){
            return returnData(0,$info);
        }
        return returnData(1,'success');
    }
}